package com.hongfasoft.util;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.hongfasoft.wx.message.Article;
import com.mysql.fabric.xmlrpc.base.Params;
import com.xinyusoft.dao.DAO;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class DBManager
{
	private static Logger log = Logger.getLogger(DBManager.class);

	public static final String WEB_URL = "http://120.24.230.222/AJZTJWeiWeb/html/";

	public static final String DB_NAME = "jztj";

	public static boolean saveWxMedia(Map dataMap) throws Exception
	{
		boolean rs = false;
		if (dataMap == null || dataMap.size() == 0)
		{
			return rs;
		}
		System.out.println("saveWxMedia\r\n" + dataMap);
		Object objs[] = new Object[7];
		objs[0] = dataMap.get("LocalUrl");
		objs[1] = dataMap.get("MsgType");
		objs[2] = dataMap.get("LocalThumb");
		objs[3] = dataMap.get("ThumbMediaId");
		objs[4] = dataMap.get("MediaId");
		objs[5] = new Date(WeixinUtil.getTime(String.valueOf(dataMap.get("CreateTime"))));
		objs[6] = dataMap.get("FromUserName");
		Object object = DAO.update(DB_NAME, DAO.getSQL("jztj.uploadMedia"), objs);
		if (object != null)
		{
			rs = true;
		}
		return rs;
	}

	public static boolean updateArticles(Map dataMap) throws Exception
	{
		boolean rs = false;
		if (dataMap == null || dataMap.size() == 0)
		{
			return rs;
		}
		Object objs[] = new Object[9];
		objs[0] = dataMap.get("stockcode");
		objs[1] = dataMap.get("stockname");
		objs[2] = dataMap.get("title");
		objs[3] = dataMap.get("imgurl");
		objs[4] = dataMap.get("content");
		objs[5] = dataMap.get("right");
		// objs[6] = dataMap.get("isreadable");
		objs[6] = dataMap.get("source");
		objs[7] = dataMap.get("author");
		objs[8] = dataMap.get("menu");
		Object object = DAO.insert(DB_NAME, DAO.getSQL("jztj.updateArticle"), objs);
		if (object != null)
		{
			rs = true;
		}
		return rs;
	}
	
	public static boolean saveArticles(Map dataMap) throws Exception
	{
		boolean rs = false;
		if (dataMap == null || dataMap.size() == 0)
		{
			return rs;
		}
		Object objs[] = new Object[9];
		objs[0] = dataMap.get("stockcode");
		objs[1] = dataMap.get("stockname");
		objs[2] = dataMap.get("title");
		objs[3] = dataMap.get("imgurl");
		objs[4] = dataMap.get("content");
		objs[5] = dataMap.get("right");
		// objs[6] = dataMap.get("isreadable");
		objs[6] = dataMap.get("source");
		objs[7] = dataMap.get("author");
		objs[8] = dataMap.get("menu");
		Object object = DAO.insert(DB_NAME, DAO.getSQL("jztj.addArticle"), objs);
		if (object != null)
		{
			rs = true;
		}
		return rs;
	}

	public static boolean checkIsMember(String wxid)
	{
		boolean isMember = false;
		try
		{
			Map m = DAO.select(DB_NAME, DAO.getSQL("jztj.checkwxmember"), new Object[] { wxid });
			isMember = (m != null && m.size() > 0);
		} catch (Exception e)
		{
			e.printStackTrace();
			log.error("会员验证失败:\r\n", e);
		}
		return isMember;
	}

	public static HashMap getArticle(String wxid, String articleid) throws Exception
	{
		HashMap article = new HashMap();
		try
		{
			article = (HashMap) DAO.select(DB_NAME, DAO.getSQL("jztj.articleInfo"), new Object[] { articleid });
			 if (article == null || article.size() == 0)
			{
				article.put("title", "文章不存在");
				article.put("content", "文章不存在");
			} else
			{
				boolean right = Boolean.valueOf(String.valueOf(article.get("F_RIGHT")));

				if (right)
				{
					Map wxmemberCheck = DAO.select(DB_NAME, DAO.getSQL("jztj.checkwxmember"), new Object[] { wxid });
					if (wxmemberCheck == null || wxmemberCheck.size() == 0)
					{
						article.put("title", "会员购买");
						article.put("content", "还不是会员哦，请  <a href=\"javascript:alert('购买会员')\">购买会员</a> 阅读文章。");
					} 
				} 
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return article;
	}

	/**
	 * 
	 * @param map
	 *            {FromUserName=ofJ-1t5zfHTuEcmYRmVadJypcJGk, EventKey=,
	 *            Event=subscribe, CreateTime=1421646424,
	 *            ToUserName=gh_8dc5741bcd9b, MsgType=event}
	 * @return
	 */
	public static boolean addFollowUser(HashMap map)
	{
		boolean result = false;
		try
		{

			Object o = DAO.update(DB_NAME, DAO.getSQL("jztj.modifyFollowUser"),
					new Object[] { map.get("userwx"), map.get("followtime"), map.get("disfollowtime") });
			result = (o != null);
		} catch (Exception e)
		{
			e.printStackTrace();
			log.error(e);
		}

		return result;
	}

	public static List<Article> stockArticleList(String wxid, boolean isMemberRight, String stockcode, String stockName, String menu)
	{
		List<Article> l = new ArrayList<Article>();
		try
		{
			String[] param = new String[] { stockcode, stockName };
			String paramSql = "";
			for (int i = 0; i < param.length; i++)
			{
				String dbcolumn = "";
				switch (i) {
				case 0:
					dbcolumn = "f_stockcode";
					break;
				case 1:
					dbcolumn = "f_stockname";
					break;
				}
				if (!StringUtils.isEmpty(param[i]))
				{
					if (i != 0 && paramSql.length() > 0)
					{
						paramSql += " AND ";
					}

					paramSql += (dbcolumn).toUpperCase() + " LIKE '%" + param[i] + "%'";
				}
			}
			List<Map> dbList;
			if (!StringUtils.isEmpty(menu))
			{
				if (isMemberRight)
				{
					dbList = DAO.selectList(DB_NAME, DAO.replaceSQL(DAO.getSQL("jztj.getMemberArticlesByStock"), new Object[] { paramSql }));
				} else
				{
					dbList = DAO.selectList(DB_NAME, DAO.replaceSQL(DAO.getSQL("jztj.getNonMemberArticlesByStock"), new Object[] { paramSql }));
				}
			} else
			{
				dbList = DAO.selectList(DB_NAME, DAO.getSQL("jztj.getArticlesByMenu"), new Object[] { menu });
			}

			for (int i = 0; dbList != null && i < dbList.size(); i++)
			{
				Map m = dbList.get(i);
				Article a = new Article();
				String title = String.valueOf(m.get("F_TITLE"));
				String imgUrl = String.valueOf(m.get("F_IMAGEURL"));
				String url = WEB_URL + "articleInfo.html?wxid=" + wxid + "&articleid=" + m.get("F_ID");
				a.setDescription(title);
				if (m.get("F_IMAGEURL") != null && StringUtils.isNotEmpty(imgUrl))
				{
					String F_IMAGEURL = getImageOuterURL(imgUrl);
					a.setPicUrl(F_IMAGEURL);
				}
				a.setTitle(title);
				a.setUrl(url);
				l.add(a);
			}

			// for (int i = 0; dbList != null && i < dbList.size(); i++)
			// {
			// Map m = dbList.get(i);
			// Article a = new Article();
			// a.setDescription(String.valueOf(m.get("F_TITLE")));
			// a.setPicUrl(String.valueOf(m.get("F_IMAGEURL")));
			// a.setTitle(String.valueOf(m.get("F_TITLE")));
			// a.setUrl(WEB_URL + "articleInfo.html?wxid=" + wxid +
			// "&articleid=" + m.get("F_ID"));
			// l.add(a);
			// }

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return l;
	}

	public static List<Article> articleList(String wxid, boolean isMemberRight, String menu)
	{
		List<Article> l = new ArrayList<Article>();
		try
		{
			List<Map> dbList;
			if (StringUtils.isEmpty(menu))
			{
				if (isMemberRight)
				{
					dbList = DAO.selectList(DB_NAME, DAO.getSQL("jztj.getMemberArticles"));
				} else
				{
					dbList = DAO.selectList(DB_NAME, DAO.getSQL("jztj.getPubArticles"));
				}
			} else
			{
				dbList = DAO.selectList(DB_NAME, DAO.getSQL("jztj.getArticlesByMenu"), new Object[] { menu });
			}

			for (int i = 0; dbList != null && i < dbList.size(); i++)
			{
				Map m = dbList.get(i);
				Article a = new Article();
				String title = String.valueOf(m.get("F_TITLE"));
				String imgUrl = String.valueOf(m.get("F_IMAGEURL"));
				String url = WEB_URL + "articleInfo.html?wxid=" + wxid + "&articleid=" + m.get("F_ID");
				a.setDescription(title);
				if (m.get("F_IMAGEURL") != null && StringUtils.isNotEmpty(imgUrl))
				{
					String F_IMAGEURL = getImageOuterURL(imgUrl);
					a.setPicUrl(F_IMAGEURL);
				}
				a.setTitle(title);
				a.setUrl(url);
				l.add(a);
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return l;
	}

	public static List<HashMap> getAllArticlList(boolean isMemberRight, String menu) throws Exception
	{
		List<HashMap> l = new ArrayList<HashMap>();
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String sql = "SELECT * FROM t_articles WHERE f_menu = ? ORDER BY f_createtime";
			List<HashMap> dbList = DAO.selectList(DB_NAME, sql, new Object[] { menu });

			for (int i = 0; dbList != null && i < dbList.size(); i++)
			{
				HashMap m = dbList.get(i);
				String imgUrl = String.valueOf(m.get("F_IMAGEURL"));
				String url = WEB_URL + "articleInfo.html?articleid=" + m.get("F_ID");
				if (m.get("F_IMAGEURL") != null && StringUtils.isNotEmpty(imgUrl))
				{
					String F_IMAGEURL = getImageOuterURL(imgUrl);
				}
				m.put("F_URL", url);
				m.put("F_IMAGEURL", imgUrl);
				m.remove("F_CONTENT");
				m.put("F_CREATETIME", sdf.format((Timestamp)m.get("F_CREATETIME")));
				l.add(m);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return l;
	}

	public static String getImageOuterURL(String imgurl)
	{
		if (StringUtils.isEmpty(imgurl))
		{
			imgurl = "../images/wxheader.jpg";
			// return null;
		}
		String[] p = imgurl.split("/");
		int totalLevel = 0;
		for (int i = 0; p != null && i < p.length; i++)
		{
			if (p[i].equalsIgnoreCase(".."))
			{
				totalLevel++;
			}
		}
		String[] s = WEB_URL.replace("http://", "").split("/");
		String outURL = "http://";
		for (int i = 0; i < s.length - totalLevel; i++)
		{
			outURL += s[i] + "/";
		}
		outURL += imgurl.replaceAll("\\.\\./", "");
		return outURL;
	}

	public static void updateLastActiveTime(String wxid)
	{
		try
		{
			DAO.update(DB_NAME, DAO.getSQL("jztj.updateLastInteractTime"), new Object[] { wxid });
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}
